package com.colin.project.jedis;

import com.colin.project.exception.impl.CodeCheckException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component

public class UserJedisOperate {
    @Autowired
    private JedisPool jedisPool;

    @Value("${my.project.param.code.expiration-time}")
    private Integer expirationTime;

    public String generateCode(String email, String code) {
        try (Jedis resource = jedisPool.getResource()) {
            if(resource.exists(email)) {
                return "error";
            }
            resource.setex(email, this.expirationTime, code);
            return "success";
        } catch (Exception e) {
            throw new CodeCheckException("验证码生成错误");
        }
    }

    public String checkCode(String code,String email) {
        try (Jedis resource = jedisPool.getResource()) {
            if (resource.get(email).equals(code)) {
                //验证码校验后删除，避免注册后忘记密码重新发验证码时报错
                resource.del(email);
                return "success";
            }
            return "error";
        } catch (Exception e) {
            throw new CodeCheckException("验证码校验错误");
        }
    }
}